package com.zmn.uac.business.impl.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zmn.tapi.common.wechat.WechatAccessToken;
import com.zmn.uac.business.interfaces.wechat.WeiChatBService;
import com.zmn.uac.client.WeChatOfficiantClient;
import com.zmn.uac.common.constant.WeChatUrlConstant;
import com.zmn.uac.model.vo.TagNamesVO;
import com.zmn.uac.util.HttpClientsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：微信第三方信息服务实现
 *
 * @author xujie
 * @since 2021/05/19 15:30
 */
@Slf4j
@Service
public class WeiChatBServiceImpl implements WeiChatBService {

    private static final String TAG = "微信第三方信息服务实现";

    @Resource
    WeChatOfficiantClient weChatOfficiantClient;

    @Override
    public String getGlobalAccessToken(String appId, String secret) {
        WechatAccessToken wechatAccessToken = weChatOfficiantClient.token(appId, secret);
        if (Objects.isNull(wechatAccessToken)) {
            log.error("[{}], 调用TAPI接口获取accessToken失败！", TAG);
            return null;
        }
        return wechatAccessToken.getToken();
    }

    @Override
    public List<TagNamesVO> getTagNames(String appId, String secret) {
        log.info("[{}], 获取微信标签信息参数:appId:{}, secret:{}", TAG, appId, secret);
        String jsonResult;
        try {
            String accessToken = getGlobalAccessToken(appId, secret);
            String requestCodeUrl = String.format(WeChatUrlConstant.WECHAT_TAGS_NAME_URL, accessToken);
            jsonResult = HttpClientsUtil.executeGet(requestCodeUrl);
        } catch (Exception e) {
            log.error("{}获取用户小程序授权code信息失败", TAG, e);
            return null;
        }
        log.info("[{}], 获取微信标签信息jsonResult: {}", TAG, jsonResult);
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        String tags = "tags";
        if (jsonObject.containsKey(tags)) {
            JSONArray jsonArray = jsonObject.getJSONArray(tags);
            if (jsonArray.isEmpty()) {
                return Collections.emptyList();
            }
            return JSONArray.parseArray(JSON.toJSONString(jsonArray), TagNamesVO.class);
        }
        return Collections.emptyList();
    }
}
